<template>
  <van-image
    :src="src"
    :width="width"
    :height="height"
    :round="round"
    :fit="mode"
    use-loading-slot
    use-error-slot
    :custom-class="avatarClass"
  >
    <view
      slot="loading"
      class="avatar-placeholder"
      :style="backgroundStyle"
    >
      <van-icon
        v-if="icon"
        :name="icon"
        class="avatar-image"
      />
      <view
        v-else
        class="avatar-text"
      >{{shortText}}</view>
    </view>
    <view
      slot="error"
      class="avatar-placeholder"
      :style="backgroundStyle"
    >
      <van-icon
        v-if="icon"
        :name="icon"
        class="avatar-image"
      />
      <view
        v-else
        class="avatar-text"
      >{{shortText}}</view>
    </view>
  </van-image>
</template>

<script>
export default {
  name: 'Avatar',
  props: {
    customClass: String,
    text: String,
    src: {
      type: String,
      default: ''
    },
    mode: {
      type: String,
      default: 'cover'
    },
    icon: String,
    size: String,
    background: String,
    width: {
      type: [String, Number],
      default: ''
    },
    height: {
      type: [String, Number],
      default: ''
    },
    round: {
      type: Boolean,
      default: true
    },
    block: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    avatarClass () {
      let classes = []
      classes.push('avatar')
      if (this.customClass) {
        classes.push(this.customClass)
      }
      if (this.size) {
        classes.push('avatar--' + this.size)
      }
      if (this.block) {
        classes.push('avatar--block')
      }
      return classes
    },
    backgroundStyle () {
      if (this.background) {
        return `background: ${this.background}`
      }
      return ''
    },
    shortText () {
      console.log('this.text', this.text)
      if (this.text) {
        const textArr = this.text.split('')
        return textArr.pop()
      }
      return this.text
    }
  },
  methods: {

  }
}
</script>

<style lang="less">
.van-image {
  vertical-align: middle;
}
.avatar {
  width: 44px;
  height: 44px;
  &--block {
    display: block !important;
  }
  &-placeholder {
    width: 100%;
    height: 100%;
    text-align: center;
    word-break: break-all;
    padding: 0 10%;
    line-height: 1.3;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f4f7ff;
  }
  &-image {
    display: flex;
    image {
      width: 40px;
      height: 40px;
      border-radius: 50%;
    }
  }
  &-text {
    font-size: 14px;
    font-weight: bold;
  }
  &--small {
    width: 34px;
    height: 34px;
  }
  &--large {
    width: 54px;
    height: 54px;
  }
}
</style>
